package com.ssy.lingxi.pay.serviceimpl;

import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.ssy.lingxi.common.constant.order.OrderPayChannelEnum;
import com.ssy.lingxi.common.constant.order.OrderPaymentParameterEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.order.api.feign.OrderFeignService;
import com.ssy.lingxi.order.api.model.vo.request.OrderPayChannelFeignVO;
import com.ssy.lingxi.order.api.model.vo.request.OrderPayParameterFeignVO;
import com.ssy.lingxi.order.api.model.vo.response.PaymentParameterFeignDetailVO;
import com.ssy.lingxi.pay.api.dto.request.aliPay.*;
import com.ssy.lingxi.pay.common.AliPayResultEnum;
import com.ssy.lingxi.pay.common.PayTypeEnum;
import com.ssy.lingxi.pay.config.PayGateWayConfig;
import com.ssy.lingxi.pay.model.assetAccount.AliPayAttachInfo;
import com.ssy.lingxi.pay.model.assetAccount.AliPayResult;
import com.ssy.lingxi.pay.service.IAliPayService;
import com.ssy.lingxi.pay.service.IPayCacheService;
import com.ssy.lingxi.pay.utils.AliPayUtil;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 支付宝支付实现类
 *
 * @author lqa
 * @version 2.0.0
 * @date 2021/11/2
 */
@Service
public class AliPayServiceImpl implements IAliPayService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private OrderFeignService orderFeignService;

    @Resource
    private IPayCacheService payCacheService;
    @Resource
    private PayGateWayConfig payGateWayConfig;

    /**
     * 扫码支付
     *
     * @param aliPayComputerRequest 接口参数
     * @param request               Http请求
     * @return 支付结果
     */
    @Override
    public AliPayResult pay(AliPayComputerRequest aliPayComputerRequest, HttpServletRequest request) {
        //从订单服务查询支付参数
        if (StringUtils.isAnyEmpty(aliPayComputerRequest.getAppId(), aliPayComputerRequest.getAlipayPublicKey(), aliPayComputerRequest.getAppPrivateKey())) {
            OrderPayParameterFeignVO feignVO = new OrderPayParameterFeignVO();
            feignVO.setMemberId(aliPayComputerRequest.getMemberId());
            feignVO.setRoleId(aliPayComputerRequest.getMemberRoleId());
            feignVO.setPayChannel(OrderPayChannelEnum.ALIPAY);
            Wrapper<PaymentParameterFeignDetailVO> parameterResult = orderFeignService.findPaymentParameters(feignVO);
            if (parameterResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                return new AliPayResult(false, String.valueOf(parameterResult.getCode()), parameterResult.getMessage());
            }

            if (CollectionUtils.isEmpty(parameterResult.getData().getParameters())) {
                return new AliPayResult(false, String.valueOf(ResponseCode.PAY_PLATFORM_PARAMETERS_DOES_NOT_EXIST.getCode()), ResponseCode.PAY_PLATFORM_PARAMETERS_DOES_NOT_EXIST.getMessage());
            }

            parameterResult.getData().getParameters().forEach(p -> {
                if (p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_APP_ID)) {
                    aliPayComputerRequest.setAppId(p.getValue());
                } else if (p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_PUBLIC_KEY)) {
                    aliPayComputerRequest.setAlipayPublicKey(p.getValue());
                } else if (p.getParameter().equals(OrderPaymentParameterEnum.APP_ALIPAY_PRIVATE_KEY)) {
                    aliPayComputerRequest.setAppPrivateKey(p.getValue());
                } else if (p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_THREAD_APP_AUTH_TOKEN)) {
                    aliPayComputerRequest.setAppAuthToken(p.getValue());
                }
            });
        }
        //生成用于缓存Key的随机字符串，并作为透传参数传递给支付宝支付，在返回时从缓存中查询秘钥信息
        if (StringUtils.isEmpty(aliPayComputerRequest.getNonce())) {
            aliPayComputerRequest.setNonce(payCacheService.randomString());
        }
        //缓存支付参数
        payCacheService.cacheAliPayParameters(aliPayComputerRequest.getMemberId(), aliPayComputerRequest.getMemberRoleId(), aliPayComputerRequest.getPayType(), aliPayComputerRequest.getNonce(), aliPayComputerRequest.getAppId(), aliPayComputerRequest.getAlipayPublicKey(), aliPayComputerRequest.getAppPrivateKey());

        //封装支付宝附加数据
        //由于支付宝附加信息最长128字符，所以改为用ObjectMapper进行序列化，同时AttachInfo的每个字段增加了@JsonProperty注解
        //这样可以简短附加数据的长度
        AliPayAttachInfo aliPayAttachInfo = new AliPayAttachInfo();
        aliPayAttachInfo.setPayType(aliPayComputerRequest.getPayType());
        aliPayAttachInfo.setMemberId(aliPayComputerRequest.getMemberId());
        aliPayAttachInfo.setMemberRoleId(aliPayComputerRequest.getMemberRoleId());
        aliPayAttachInfo.setAttach(aliPayComputerRequest.getBody());
        aliPayAttachInfo.setServiceType(aliPayComputerRequest.getServiceType());
        aliPayAttachInfo.setNonce(aliPayComputerRequest.getNonce());
        String attachJson = payCacheService.serializeObject(aliPayAttachInfo);
        try {
            //参数配置
            AlipayConfig alipayConfig = new AlipayConfig();
            alipayConfig.setServerUrl(AliPayUtil.gatewayUrl);
            alipayConfig.setAppId(aliPayComputerRequest.getAppId());
            alipayConfig.setPrivateKey(aliPayComputerRequest.getAppPrivateKey());
            alipayConfig.setAlipayPublicKey(aliPayComputerRequest.getAlipayPublicKey());
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            //请求参数
            AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();
            //支付宝第三方应用调用时使用
            if (aliPayComputerRequest.getPayType().equals(PayTypeEnum.Member.getCode())) {
                alipayTradePagePayRequest.putOtherTextParam("app_auth_token", aliPayComputerRequest.getAppAuthToken());
            }
            //请求实体
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.setOutTradeNo(aliPayComputerRequest.getOrderCode());   //商户订单号
            model.setTotalAmount(aliPayComputerRequest.getPayMoney() + "");//订单总金额
            model.setSubject(aliPayComputerRequest.getRemark());         //订单标题
            model.setBody(attachJson);                                   //用作回调校验
            model.setProductCode(AliPayUtil.productCode);         //产品码:当面支付
            model.setQrPayMode("0");                                     //PC扫码支付的方式
            alipayTradePagePayRequest.setBizModel(model);
            alipayTradePagePayRequest.setNotifyUrl(payGateWayConfig.getNotifyUrl() + AliPayUtil.notifyUrl);//回调地址
            AlipayTradePagePayResponse response = alipayClient.pageExecute(alipayTradePagePayRequest);
            if (StringUtil.isNotEmpty(response.getBody())) {
                return new AliPayResult(true, response.getCode(), response.getBody());
            } else {
                return new AliPayResult(false, response.getCode(), response.getSubMsg());
            }
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALIPAY_FAILED, e.getMessage());
        }
    }

    /**
     * 支付宝app支付
     *
     * @param aliPayComputerRequest 请求参数
     * @param request               HttpServletRequest
     * @return 操作结果
     */
    @Override
    public AliPayResult appPay(AliPayComputerRequest aliPayComputerRequest, HttpServletRequest request) {
        //从订单服务查询支付参数
        if (StringUtils.isAnyEmpty(aliPayComputerRequest.getAppId(), aliPayComputerRequest.getAlipayPublicKey(), aliPayComputerRequest.getAppPrivateKey())) {
            OrderPayParameterFeignVO feignVO = new OrderPayParameterFeignVO();
            feignVO.setMemberId(aliPayComputerRequest.getMemberId());
            feignVO.setRoleId(aliPayComputerRequest.getMemberRoleId());
            feignVO.setPayChannel(OrderPayChannelEnum.ALIPAY);
            Wrapper<PaymentParameterFeignDetailVO> parameterResult = orderFeignService.findPaymentParameters(feignVO);
            if (parameterResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                return new AliPayResult(false, String.valueOf(parameterResult.getCode()), parameterResult.getMessage());
            }

            if (CollectionUtils.isEmpty(parameterResult.getData().getParameters())) {
                return new AliPayResult(false, String.valueOf(ResponseCode.PAY_PLATFORM_PARAMETERS_DOES_NOT_EXIST.getCode()), ResponseCode.PAY_PLATFORM_PARAMETERS_DOES_NOT_EXIST.getMessage());
            }

            parameterResult.getData().getParameters().forEach(p -> {
                if (p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_APP_ID)) {
                    aliPayComputerRequest.setAppId(p.getValue());
                } else if (p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_PUBLIC_KEY)) {
                    aliPayComputerRequest.setAlipayPublicKey(p.getValue());
                } else if (p.getParameter().equals(OrderPaymentParameterEnum.APP_ALIPAY_PRIVATE_KEY)) {
                    aliPayComputerRequest.setAppPrivateKey(p.getValue());
                }
            });
        }
        //生成用于缓存Key的随机字符串，并作为透传参数传递给支付宝支付，在返回时从缓存中查询秘钥信息
        if (StringUtils.isEmpty(aliPayComputerRequest.getNonce())) {
            aliPayComputerRequest.setNonce(payCacheService.randomString());
        }
        //缓存支付参数
        payCacheService.cacheAliPayParameters(aliPayComputerRequest.getMemberId(), aliPayComputerRequest.getMemberRoleId(), aliPayComputerRequest.getPayType(), aliPayComputerRequest.getNonce(), aliPayComputerRequest.getAppId(), aliPayComputerRequest.getAlipayPublicKey(), aliPayComputerRequest.getAppPrivateKey());

        //封装支付宝附加数据
        //由于支付宝附加信息最长128字符，所以改为用ObjectMapper进行序列化，同时AttachInfo的每个字段增加了@JsonProperty注解
        //这样可以简短附加数据的长度
        AliPayAttachInfo aliPayAttachInfo = new AliPayAttachInfo();
        aliPayAttachInfo.setPayType(aliPayComputerRequest.getPayType());
        aliPayAttachInfo.setMemberId(aliPayComputerRequest.getMemberId());
        aliPayAttachInfo.setMemberRoleId(aliPayComputerRequest.getMemberRoleId());
        aliPayAttachInfo.setAttach(aliPayComputerRequest.getBody());
        aliPayAttachInfo.setServiceType(aliPayComputerRequest.getServiceType());
        aliPayAttachInfo.setNonce(aliPayComputerRequest.getNonce());
        String attachJson = payCacheService.serializeObject(aliPayAttachInfo);
        try {
            //参数配置
            AlipayConfig alipayConfig = new AlipayConfig();
            alipayConfig.setServerUrl(AliPayUtil.gatewayUrl);
            alipayConfig.setAppId(aliPayComputerRequest.getAppId());
            alipayConfig.setPrivateKey(aliPayComputerRequest.getAppPrivateKey());
            alipayConfig.setAlipayPublicKey(aliPayComputerRequest.getAlipayPublicKey());
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            //请求参数
            AlipayTradeAppPayRequest alipayTradeAppPayRequest = new AlipayTradeAppPayRequest();
            //支付宝第三方应用调用时使用
            if (aliPayComputerRequest.getPayType().equals(PayTypeEnum.Member.getCode())) {
                alipayTradeAppPayRequest.putOtherTextParam("app_auth_token", aliPayComputerRequest.getAppAuthToken());
            }
            //请求实体
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.setOutTradeNo(aliPayComputerRequest.getOrderCode());   //商户订单号
            model.setTotalAmount(aliPayComputerRequest.getPayMoney() + "");//订单总金额
            model.setSubject(aliPayComputerRequest.getRemark());         //订单标题
            model.setBody(attachJson);                                   //用作回调校验
            alipayTradeAppPayRequest.setBizModel(model);
            alipayTradeAppPayRequest.setNotifyUrl(payGateWayConfig.getNotifyUrl() + AliPayUtil.notifyUrl);//回调地址
            AlipayTradeAppPayResponse response = alipayClient.pageExecute(alipayTradeAppPayRequest, "GET");//返回url
            if (StringUtil.isNotEmpty(response.getBody())) {
                return new AliPayResult(true, response.getCode(), response.getBody());
            } else {
                return new AliPayResult(false, response.getCode(), response.getSubMsg());
            }
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALIPAY_FAILED, e.getMessage());
        }
    }

    /**
     * 支付宝手机网站支付
     *
     * @param aliPayComputerRequest 接口参数
     * @param request               request请求体
     * @return 操作结果
     */
    @Override
    public AliPayResult jsApiPay(AliPayComputerRequest aliPayComputerRequest, HttpServletRequest request) {
        //从订单服务查询支付参数
        if (StringUtils.isAnyEmpty(aliPayComputerRequest.getAppId(), aliPayComputerRequest.getAlipayPublicKey(), aliPayComputerRequest.getAppPrivateKey())) {
            OrderPayParameterFeignVO feignVO = new OrderPayParameterFeignVO();
            feignVO.setMemberId(aliPayComputerRequest.getMemberId());
            feignVO.setRoleId(aliPayComputerRequest.getMemberRoleId());
            feignVO.setPayChannel(OrderPayChannelEnum.ALIPAY);
            Wrapper<PaymentParameterFeignDetailVO> parameterResult = orderFeignService.findPaymentParameters(feignVO);
            if (parameterResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                return new AliPayResult(false, String.valueOf(parameterResult.getCode()), parameterResult.getMessage());
            }

            if (CollectionUtils.isEmpty(parameterResult.getData().getParameters())) {
                return new AliPayResult(false, String.valueOf(ResponseCode.PAY_PLATFORM_PARAMETERS_DOES_NOT_EXIST.getCode()), ResponseCode.PAY_PLATFORM_PARAMETERS_DOES_NOT_EXIST.getMessage());
            }

            parameterResult.getData().getParameters().forEach(p -> {
                if (p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_APP_ID)) {
                    aliPayComputerRequest.setAppId(p.getValue());
                } else if (p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_PUBLIC_KEY)) {
                    aliPayComputerRequest.setAlipayPublicKey(p.getValue());
                } else if (p.getParameter().equals(OrderPaymentParameterEnum.APP_ALIPAY_PRIVATE_KEY)) {
                    aliPayComputerRequest.setAppPrivateKey(p.getValue());
                }
            });
        }
        //生成用于缓存Key的随机字符串，并作为透传参数传递给支付宝支付，在返回时从缓存中查询秘钥信息
        if (StringUtils.isEmpty(aliPayComputerRequest.getNonce())) {
            aliPayComputerRequest.setNonce(payCacheService.randomString());
        }
        //缓存支付参数
        payCacheService.cacheAliPayParameters(aliPayComputerRequest.getMemberId(), aliPayComputerRequest.getMemberRoleId(), aliPayComputerRequest.getPayType(), aliPayComputerRequest.getNonce(), aliPayComputerRequest.getAppId(), aliPayComputerRequest.getAlipayPublicKey(), aliPayComputerRequest.getAppPrivateKey());

        //封装支付宝附加数据
        //由于支付宝附加信息最长128字符，所以改为用ObjectMapper进行序列化，同时AttachInfo的每个字段增加了@JsonProperty注解
        //这样可以简短附加数据的长度
        AliPayAttachInfo aliPayAttachInfo = new AliPayAttachInfo();
        aliPayAttachInfo.setPayType(aliPayComputerRequest.getPayType());
        aliPayAttachInfo.setMemberId(aliPayComputerRequest.getMemberId());
        aliPayAttachInfo.setMemberRoleId(aliPayComputerRequest.getMemberRoleId());
        aliPayAttachInfo.setAttach(aliPayComputerRequest.getBody());
        aliPayAttachInfo.setServiceType(aliPayComputerRequest.getServiceType());
        aliPayAttachInfo.setNonce(aliPayComputerRequest.getNonce());
        String attachJson = payCacheService.serializeObject(aliPayAttachInfo);
        try {
            //参数配置
            AlipayConfig alipayConfig = new AlipayConfig();
            alipayConfig.setServerUrl(AliPayUtil.gatewayUrl);
            alipayConfig.setAppId(aliPayComputerRequest.getAppId());
            alipayConfig.setPrivateKey(aliPayComputerRequest.getAppPrivateKey());
            alipayConfig.setAlipayPublicKey(aliPayComputerRequest.getAlipayPublicKey());
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            //请求参数
            AlipayTradeWapPayRequest alipayTradeWapPayRequest = new AlipayTradeWapPayRequest();
            //支付宝第三方应用调用时使用
            if (aliPayComputerRequest.getPayType().equals(PayTypeEnum.Member.getCode())) {
                alipayTradeWapPayRequest.putOtherTextParam("app_auth_token", aliPayComputerRequest.getAppAuthToken());
            }
            //请求实体
            AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
            model.setOutTradeNo(aliPayComputerRequest.getOrderCode());   //商户订单号
            model.setTotalAmount(aliPayComputerRequest.getPayMoney() + "");//订单总金额
            model.setSubject(aliPayComputerRequest.getRemark());         //订单标题
            model.setBody(attachJson);                                   //用作回调校验
            alipayTradeWapPayRequest.setBizModel(model);
            alipayTradeWapPayRequest.setNotifyUrl(payGateWayConfig.getNotifyUrl() + AliPayUtil.notifyUrl);//回调地址
            AlipayTradeWapPayResponse response = alipayClient.pageExecute(alipayTradeWapPayRequest);
            if (StringUtil.isNotEmpty(response.getBody())) {
                return new AliPayResult(true, response.getCode(), response.getBody());
            } else {
                return new AliPayResult(false, response.getCode(), response.getSubMsg());
            }
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALIPAY_FAILED, e.getMessage());
        }
    }

    /**
     * 查询订单
     *
     * @param aliPayOrderQueryRequest 查询支付宝支付订单
     * @return 查询结果
     */
    @Override
    public AliPayResult orderQuery(AliPayOrderQueryRequest aliPayOrderQueryRequest) {
        try {
            //获取参数
            Long memberId = aliPayOrderQueryRequest.getMemberId();
            Long memberRoleId = aliPayOrderQueryRequest.getMemberRoleId();
            String outTradeNo = aliPayOrderQueryRequest.getOutTradeNo();
            String transactionId = aliPayOrderQueryRequest.getTransactionId();
            String orgPid = aliPayOrderQueryRequest.getOrgPid();
            Integer payType = aliPayOrderQueryRequest.getPayType();
            //从订单服务查询支付参数
            OrderPayParameterFeignVO feignVO = new OrderPayParameterFeignVO();
            feignVO.setMemberId(memberId);
            feignVO.setRoleId(memberRoleId);
            feignVO.setPayChannel(OrderPayChannelEnum.ALIPAY);
            Wrapper<PaymentParameterFeignDetailVO> parameterResult = orderFeignService.findPaymentParameters(feignVO);
            if (parameterResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                return new AliPayResult(false, String.valueOf(parameterResult.getCode()), parameterResult.getMessage());
            }

            if (CollectionUtils.isEmpty(parameterResult.getData().getParameters())) {
                return new AliPayResult(false, String.valueOf(ResponseCode.PAY_PLATFORM_PARAMETERS_DOES_NOT_EXIST.getCode()), ResponseCode.PAY_PLATFORM_PARAMETERS_DOES_NOT_EXIST.getMessage());
            }
            //参数配置
            AlipayConfig alipayConfig = new AlipayConfig();
            //从订单服务中获取动态配置
           /* String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDRjrdW9XaMOKXkV5padfziD8sIxiNFUXepjz4CKt+rSRJNUDSz/3+Eviu0HfJdro1iGI/qbLFcJeo3Mk6LRT2Y68B2l33anjX3x3pZEvjQJmwLuvC5kLb7i9mYFWRMTS14mWlGEQDCDyJYHSZXJrVDU/BMn4fQH0KM01+/tvFnXqnGp111gYtEVwc7WTSWtqwR4nSUxtNHY8Gxkb6n7g5np5jYLRwY1W4tx3yVE5/FuYeR8lysl0A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ExL4Ce/j30qy1vrj5WN7/tL0+H/aVvzMD6kT1euRlVSIs+Q0hH5GQnUUDx+kLJBAoGAFdUdC7oszUxhyHoC3Tk2FR9g5M28RNb+C+Iep2gsEU91H1s/Hvq2WkFAiqReSX1Xf28tzDVpHaipQVCAERx64MSm2XIZJeaulR5m55U5zKbc+InhdVrnQKfiICXlsjwRn6fpxwZ6APhQ//Qm9CgU4kKv9ChJcLyhsa1Q/rZr1xw=";
            String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkDl4qfoTCbqkwva73sRkflg6OKwZ43V9WonRos6LKD5DjR44pNo87ZqGQH3YA/oHtbvdJakJJmfHC2hrtIv8z+wEjzQPE0YOUZ3PCA5MzkivGqDTUKy6h6mQ/uq4Ra+C03aN8w5uphBQuX++CEtHzLPQMoGgrzz5zrgim5XyaxbxoKFoOOqzCwoo2qFljGZ3nWIttobvP8zSWcS1qGPxSQxnfa0jXn1DZhCuaPH55W1J82W5UAx2UPHpQAwUjD8Wu0cfW+ZoLhyNNSEfYTu9+mgSQYDOA2dV+cJwWltO2zdZED/ii6VptUUz8qWu1HcdNR19m5T1GAkTJx475b9eIQIDAQAB";
            alipayConfig.setAppId("2021002190673720");
            alipayConfig.setPrivateKey(privateKey);
            alipayConfig.setAlipayPublicKey(alipayPublicKey);*/
            parameterResult.getData().getParameters().stream().filter(p -> p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_APP_ID)).findFirst().ifPresent(p -> alipayConfig.setAppId(p.getValue()));
            parameterResult.getData().getParameters().stream().filter(p -> p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_PUBLIC_KEY)).findFirst().ifPresent(p -> alipayConfig.setAlipayPublicKey(p.getValue()));
            parameterResult.getData().getParameters().stream().filter(p -> p.getParameter().equals(OrderPaymentParameterEnum.APP_ALIPAY_PRIVATE_KEY)).findFirst().ifPresent(p -> alipayConfig.setPrivateKey(p.getValue()));
            alipayConfig.setServerUrl(AliPayUtil.gatewayUrl);
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            //统一收单线下交易查询对象:AlipayTradeQueryRequest
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            //自定义请求参数
            AlipayTradeQueryModel model = new AlipayTradeQueryModel();
            model.setOutTradeNo(outTradeNo);                               //商户订单号      二者必须传其中一个,同时传trade_no优先级高
            model.setTradeNo(transactionId);                               //支付宝交易号
            //  model.setOrgPid(orgPid); //银行间联模式下有用，其它场景请不要使用
            request.setBizModel(model);
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            //验证返回结果
            if (response != null) {
                String returnCode = response.getCode();
                if (AliPayResultEnum.SUCCESS.getCode().equals(returnCode)) {
                    //验证结果
                    return new AliPayResult(true, response.getCode(), response.getBody());
                } else {
                    return new AliPayResult(false, response.getCode(), response.getSubMsg());
                }
            } else {
                return new AliPayResult(false, AliPayUtil.QUERY_ORDER_FILED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new AliPayResult(false, e.getMessage());
        }
    }


    /**
     * 申请退款
     */
    @Override
    public AliPayResult refund(AliPayRefundRequest aliPayRefundRequest) {
        try {
            //获取参数
            Long memberRoleId = aliPayRefundRequest.getMemberRoleId();
            String outTradeNo = aliPayRefundRequest.getOutTradeNo();
            String transactionId = aliPayRefundRequest.getTransactionId();
            String outRefundNo = aliPayRefundRequest.getOutRefundNo();
            Double refundMoney = aliPayRefundRequest.getRefundMoney();
            String refundReason = aliPayRefundRequest.getRefundReason();
            Integer payType = aliPayRefundRequest.getPayType();

            //从订单服务查询支付参数
            //平台支付参数
            if (payType.equals(PayTypeEnum.Platform.getCode()) && StringUtils.isAnyEmpty(aliPayRefundRequest.getAppId(), aliPayRefundRequest.getPublicKey(), aliPayRefundRequest.getPrivateKey())) {
                OrderPayChannelFeignVO feignVO = new OrderPayChannelFeignVO();
                feignVO.setPayChannel(OrderPayChannelEnum.ALIPAY);
                Wrapper<PaymentParameterFeignDetailVO> platformResult = orderFeignService.findPlatformPaymentParameters(feignVO);
                if (platformResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                    return new AliPayResult(false, String.valueOf(platformResult.getCode()), platformResult.getMessage());
                }

                if (CollectionUtils.isEmpty(platformResult.getData().getParameters())) {
                    return new AliPayResult(false, String.valueOf(ResponseCode.PAY_PLATFORM_PARAMETERS_DOES_NOT_EXIST.getCode()), ResponseCode.PAY_PLATFORM_PARAMETERS_DOES_NOT_EXIST.getMessage());
                }

                platformResult.getData().getParameters().stream().filter(p -> p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_APP_ID)).findFirst().ifPresent(p -> aliPayRefundRequest.setAppId(p.getValue()));
                platformResult.getData().getParameters().stream().filter(p -> p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_PUBLIC_KEY)).findFirst().ifPresent(p -> aliPayRefundRequest.setPublicKey(p.getValue()));
                platformResult.getData().getParameters().stream().filter(p -> p.getParameter().equals(OrderPaymentParameterEnum.APP_ALIPAY_PRIVATE_KEY)).findFirst().ifPresent(p -> aliPayRefundRequest.setPrivateKey(p.getValue()));
            }

            //会员支付参数
            if (payType.equals(PayTypeEnum.Member.getCode()) && StringUtils.isAnyEmpty(aliPayRefundRequest.getAppId(), aliPayRefundRequest.getPublicKey(), aliPayRefundRequest.getPrivateKey(), aliPayRefundRequest.getAppAuthToken())) {
                OrderPayParameterFeignVO feignVO = new OrderPayParameterFeignVO();
                feignVO.setMemberId(aliPayRefundRequest.getMemberId());
                feignVO.setRoleId(aliPayRefundRequest.getMemberRoleId());
                feignVO.setPayChannel(OrderPayChannelEnum.ALIPAY);
                Wrapper<PaymentParameterFeignDetailVO> memberResult = orderFeignService.findMemberPaymentParameters(feignVO);
                if (memberResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                    return new AliPayResult(false, String.valueOf(memberResult.getCode()), memberResult.getMessage());
                }

                if (CollectionUtils.isEmpty(memberResult.getData().getParameters())) {
                    return new AliPayResult(false, String.valueOf(ResponseCode.PAY_PLATFORM_PARAMETERS_DOES_NOT_EXIST.getCode()), ResponseCode.PAY_PLATFORM_PARAMETERS_DOES_NOT_EXIST.getMessage());
                }

                memberResult.getData().getParameters().stream().filter(p -> p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_APP_ID)).findFirst().ifPresent(p -> aliPayRefundRequest.setAppId(p.getValue()));
                memberResult.getData().getParameters().stream().filter(p -> p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_PUBLIC_KEY)).findFirst().ifPresent(p -> aliPayRefundRequest.setPublicKey(p.getValue()));
                memberResult.getData().getParameters().stream().filter(p -> p.getParameter().equals(OrderPaymentParameterEnum.APP_ALIPAY_PRIVATE_KEY)).findFirst().ifPresent(p -> aliPayRefundRequest.setPrivateKey(p.getValue()));
                memberResult.getData().getParameters().stream().filter(p -> p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_THREAD_APP_AUTH_TOKEN)).findFirst().ifPresent(p -> aliPayRefundRequest.setAppAuthToken(p.getValue()));
            }

            //参数配置
            AlipayConfig alipayConfig = new AlipayConfig();
            alipayConfig.setAppId(aliPayRefundRequest.getAppId());
            alipayConfig.setAlipayPublicKey(aliPayRefundRequest.getPublicKey());
            alipayConfig.setPrivateKey(aliPayRefundRequest.getPrivateKey());

            //从订单服务中获取动态配置
   /*       String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDRjrdW9XaMOKXkV5padfziD8sIxiNFUXepjz4CKt+rSRJNUDSz/3+Eviu0HfJdro1iGI/qbLFcJeo3Mk6LRT2Y68B2l33anjX3x3pZEvjQJmwLuvC5kLb7i9mYFWRMTS14mWlGEQDCDyJYHSZXJrVDU/BMn4fQH0KM01+/tvFnXqnGp111gYtEVwc7WTSWtqwR4nSUxtNHY8Gxkb6n7g5np5jYLRwY1W4tx3yVE5/FuYeR8lysl0A0wXcE3UvJPM6tXMDGXWd5OMJie51XM5Mcx9GsfAVmux2WKnJZTZGivSWo1PXaoX3KsUtVHSmxWDkcxDW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yHoC3Tk2FR9g5M28RNb+C+Iep2gsEU91H1s/Hvq2WkFAiqReSX1Xf28tzDVpHaipQVCAERx64MSm2XIZJeaulR5m55U5zKbc+InhdVrnQKfiICXlsjwRn6fpxwZ6APhQ//Qm9CgU4kKv9ChJcLyhsa1Q/rZr1xw=";
            String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkDl4qfoTCbqkwva73sRkflg6OKwZ43V9WonRos6LKD5DjR44pNo87ZqGQH3YA/oHtbvdJakJJmfHC2hrtIv8z+wEjzQPE0YOUZ3PCA5MzkivGqDTUKy6h6mQ/uq4Ra+C03aN8w5uphBQuX++CEtHzLPQMoGgrzz5zrgim5XyaxbxoKFoOOqzCwoo2qFljGZ3nWIttobvP8zSWcS1qGPxSQxnfa0jXn1DZhCuaPH55W1J82W5UAx2UPHpQAwUjD8Wu0cfW+ZoLhyNNSEfYTu9+mgSQYDOA2dV+cJwWltO2zdZED/ii6VptUUz8qWu1HcdNR19m5T1GAkTJx475b9eIQIDAQAB";
            alipayConfig.setAppId("2021002190673720");
            alipayConfig.setPrivateKey(privateKey);
            alipayConfig.setAlipayPublicKey(alipayPublicKey);*/

            //固定配置
            alipayConfig.setServerUrl(AliPayUtil.gatewayUrl);
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            //统一收单交易退款对象
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            //第三方应用时使用
            if (aliPayRefundRequest.getPayType().equals(PayTypeEnum.Member.getCode())) {
                request.putOtherTextParam("app_auth_token", aliPayRefundRequest.getAppAuthToken());
            }
            //自定义请求参数
            AlipayTradeRefundModel model = new AlipayTradeRefundModel();
            model.setOutTradeNo(transactionId);                          //商户订单号
            // model.setTradeNo(transactionId);                          //支付宝交易号
            model.setRefundAmount(String.valueOf(refundMoney));       //退款金额
            model.setOutRequestNo(outRefundNo);                       //退款请求号
            model.setRefundReason(refundReason);                       //退款原因
            request.setBizModel(model);
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            //验证返回结果
            if (response != null) {
                String returnCode = response.getCode();
                if (AliPayResultEnum.SUCCESS.getCode().equals(returnCode)) {
                    //验证结果
                    return new AliPayResult(true, response.getCode(), response.getCode());
                } else {
                    return new AliPayResult(false, response.getCode(), response.getSubMsg());
                }
            } else {
                return new AliPayResult(false, AliPayUtil.APPLY_REFUND_FILED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new AliPayResult(false, e.getMessage());
        }
    }

    /**
     * 退款查询
     *
     * @param aliPayRefundQueryRequest 支付宝退款信息
     * @return 查询结果
     */
    @Override
    public AliPayResult refundQuery(AliPayRefundQueryRequest aliPayRefundQueryRequest) {
        try {
            //获取参数
            Long memberId = aliPayRefundQueryRequest.getMemberId();
            Long memberRoleId = aliPayRefundQueryRequest.getMemberRoleId();
            String outTradeNo = aliPayRefundQueryRequest.getOutTradeNo();
            String transactionId = aliPayRefundQueryRequest.getTransactionId();
            String outRefundNo = aliPayRefundQueryRequest.getOutRefundNo();
            Integer payType = aliPayRefundQueryRequest.getPayType();
            //从订单服务查询支付参数
            OrderPayParameterFeignVO feignVO = new OrderPayParameterFeignVO();
            feignVO.setMemberId(memberId);
            feignVO.setRoleId(memberRoleId);
            feignVO.setPayChannel(OrderPayChannelEnum.ALIPAY);
            Wrapper<PaymentParameterFeignDetailVO> parameterResult = orderFeignService.findPaymentParameters(feignVO);
            if (parameterResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                return new AliPayResult(false, String.valueOf(parameterResult.getCode()), parameterResult.getMessage());
            }

            if (CollectionUtils.isEmpty(parameterResult.getData().getParameters())) {
                return new AliPayResult(false, String.valueOf(ResponseCode.PAY_PLATFORM_PARAMETERS_DOES_NOT_EXIST.getCode()), ResponseCode.PAY_PLATFORM_PARAMETERS_DOES_NOT_EXIST.getMessage());
            }

            //参数配置
            AlipayConfig alipayConfig = new AlipayConfig();
          /*  String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwgg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gRwBwnlvXhnfVJzZ4hI6iVx4E+wRJXa5dtOA89f+ZUODQbIZ3tdvOM6Vme3Nk0VUC7O1DaggCuPsUdaMfiKR++/CKLs64njuHtuswtNa0t7pMP54AvY9Ot/dOzvy1Gku/EUpELPy5dNQO4FaQKBgDHoTRh3h0GczOihHSNvn1NSddv3fb/lyz7tmUs3LfTdwPAlJgbLixwNMzGlOJWtuQkcCLG2d0NhXNuaL43+EZMS+Ozn6j5uUYfXtuFad+FINExL4Ce/j30qy1vrj5WN7/tL0+H/aVvzMD6kT1euRlVSIs+Q0hH5GQnUUDx+kLJBAoGAFdUdC7oszUxhyHoC3Tk2FR9g5M28RNb+C+Iep2gsEU91H1s/Hvq2WkFAiqReSX1Xf28tzDVpHaipQVCAERx64MSm2XIZJeaulR5m55U5zKbc+InhdVrnQKfiICXlsjwRn6fpxwZ6APhQ//Qm9CgU4kKv9ChJcLyhsa1Q/rZr1xw=";
            String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkDl4qfoTCbqkwva73sRkflg6OKwZ43V9WonRos6LKD5DjR44pNo87ZqGQH3YA/oHtbvdJakJJmfHC2hrtIv8z+wEjzQPE0YOUZ3PCA5MzkivGqDTUKy6h6mQ/uq4Ra+C03aN8w5uphBQuX++CEtHzLPQMoGgrzz5zrgim5XyaxbxoKFoOOqzCwoo2qFljGZ3nWIttobvP8zSWcS1qGPxSQxnfa0jXn1DZhCuaPH55W1J82W5UAx2UPHpQAwUjD8Wu0cfW+ZoLhyNNSEfYTu9+mgSQYDOA2dV+cJwWltO2zdZED/ii6VptUUz8qWu1HcdNR19m5T1GAkTJx475b9eIQIDAQAB";
            alipayConfig.setAppId("2021002190673720");
            alipayConfig.setPrivateKey(privateKey);
            alipayConfig.setAlipayPublicKey(alipayPublicKey);*/
            parameterResult.getData().getParameters().stream().filter(p -> p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_APP_ID)).findFirst().ifPresent(p -> alipayConfig.setAppId(p.getValue()));
            parameterResult.getData().getParameters().stream().filter(p -> p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_PUBLIC_KEY)).findFirst().ifPresent(p -> alipayConfig.setAlipayPublicKey(p.getValue()));
            parameterResult.getData().getParameters().stream().filter(p -> p.getParameter().equals(OrderPaymentParameterEnum.APP_ALIPAY_PRIVATE_KEY)).findFirst().ifPresent(p -> alipayConfig.setPrivateKey(p.getValue()));
            //固定配置
            alipayConfig.setServerUrl(AliPayUtil.gatewayUrl);
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            //统一收单交易退款查询对象:AlipayTradeFastpayRefundQueryRequest
            AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
            //自定义请求参数
            AlipayTradeFastpayRefundQueryModel model = new AlipayTradeFastpayRefundQueryModel();
            model.setOutTradeNo(outTradeNo);        //商户订单号
            model.setTradeNo(transactionId);        //支付宝交易号
            model.setOutRequestNo(outRefundNo);     //退款请求号(请求退款接口时，传入的退款请求号，如果在退款请求时未传入，则该值为创建交易时的商户订单号。)
            request.setBizModel(model);
            AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
            //验证返回结果
            if (response != null) {
                String returnCode = response.getCode();
                if (AliPayResultEnum.REFUND_SUCCESS.getCode().equals(returnCode)) {
                    //验证支付结果
                    return new AliPayResult(true, response.getCode(), response.getBody());
                } else {
                    return new AliPayResult(false, response.getCode(), response.getSubMsg());
                }
            } else {
                return new AliPayResult(false, AliPayUtil.QUERY_REFUND_FILED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new AliPayResult(false, e.getMessage());
        }
    }

    /**
     * 关闭交易
     *
     * @param aliPayCloseOrderRequest 支付宝关闭交易请求体
     * @return 关闭结果
     */

    @Override
    public AliPayResult closeOrder(AliPayCloseOrderRequest aliPayCloseOrderRequest) {
        try {
            //获取参数
            Long memberId = aliPayCloseOrderRequest.getMemberId();
            Long memberRoleId = aliPayCloseOrderRequest.getMemberRoleId();
            String outTradeNo = aliPayCloseOrderRequest.getOutTradeNo();
            String tradeNo = aliPayCloseOrderRequest.getTradeNo();
            Long operateId = aliPayCloseOrderRequest.getOperateId();
            Integer payType = aliPayCloseOrderRequest.getPayType();

            //从订单服务查询支付参数
            OrderPayParameterFeignVO feignVO = new OrderPayParameterFeignVO();
            feignVO.setMemberId(memberId);
            feignVO.setRoleId(memberRoleId);
            feignVO.setPayChannel(OrderPayChannelEnum.ALIPAY);
            Wrapper<PaymentParameterFeignDetailVO> parameterResult = orderFeignService.findPaymentParameters(feignVO);
            if (parameterResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                return new AliPayResult(false, String.valueOf(parameterResult.getCode()), parameterResult.getMessage());
            }

            if (CollectionUtils.isEmpty(parameterResult.getData().getParameters())) {
                return new AliPayResult(false, String.valueOf(ResponseCode.PAY_PLATFORM_PARAMETERS_DOES_NOT_EXIST.getCode()), ResponseCode.PAY_PLATFORM_PARAMETERS_DOES_NOT_EXIST.getMessage());
            }
            //参数配置
            AlipayConfig alipayConfig = new AlipayConfig();
       /*     String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDRjrdW9XaMOKXkV5padfziD8sIxiNFUXepjz4CKt+rSRJNUDSz/3+Eviu0HfJdro1iGI/qbLFcJeo3Mk6LRT2Y68B2l33anjX3x3pZEvjQJmwLuvC5kLb7i9mYFWRMTS14mWlGEQDCDyJYHSZXJrVDU/BMn4fQH0KM01+/tvFnXqnGp111gYtEVwc7WTSWtqwR4nSUxtNHY8Gxkb6n7g5np5jYLRwY1W4tx3yVE5/FuYeR8lysl0A0wXcE3UvJPM6tXMDGXWd5OMJie51XM5Mcx9GsfAVmux2WKnJZTZGivSWo1PXaoX3KsUtVHSmxWDkcxDWM320w5rH77p0gJIsfAgMBAAECggEAFZO4VP/ZQP7kNeq/PelALJartS+RmiWVSKQzIk3/0ccoV0WW56G7I5PhNB6RQgwjCqK0ztJ6QJ62yxAm/jgW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jwRn6fpxwZ6APhQ//Qm9CgU4kKv9ChJcLyhsa1Q/rZr1xw=";
            String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkDl4qfoTCbqkwva73sRkflg6OKwZ43V9WonRos6LKD5DjR44pNo87ZqGQH3YA/oHtbvdJakJJmfHC2hrtIv8z+wEjzQPE0YOUZ3PCA5MzkivGqDTUKy6h6mQ/uq4Ra+C03aN8w5uphBQuX++CEtHzLPQMoGgrzz5zrgim5XyaxbxoKFoOOqzCwoo2qFljGZ3nWIttobvP8zSWcS1qGPxSQxnfa0jXn1DZhCuaPH55W1J82W5UAx2UPHpQAwUjD8Wu0cfW+ZoLhyNNSEfYTu9+mgSQYDOA2dV+cJwWltO2zdZED/ii6VptUUz8qWu1HcdNR19m5T1GAkTJx475b9eIQIDAQAB";
            alipayConfig.setAppId("2021002190673720");
            alipayConfig.setPrivateKey(privateKey);
            alipayConfig.setAlipayPublicKey(alipayPublicKey);*/
            //从订单服务中获取动态配置
            parameterResult.getData().getParameters().stream().filter(p -> p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_APP_ID)).findFirst().ifPresent(p -> alipayConfig.setAppId(p.getValue()));
            parameterResult.getData().getParameters().stream().filter(p -> p.getParameter().equals(OrderPaymentParameterEnum.ALIPAY_PUBLIC_KEY)).findFirst().ifPresent(p -> alipayConfig.setAlipayPublicKey(p.getValue()));
            parameterResult.getData().getParameters().stream().filter(p -> p.getParameter().equals(OrderPaymentParameterEnum.APP_ALIPAY_PRIVATE_KEY)).findFirst().ifPresent(p -> alipayConfig.setPrivateKey(p.getValue()));
            //固定配置
            alipayConfig.setServerUrl(AliPayUtil.gatewayUrl);
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            //统一收单交易关闭对象:AlipayTradeCloseRequest
            AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
            //自定义请求参数
            AlipayTradeCloseModel model = new AlipayTradeCloseModel();
            model.setOutTradeNo(outTradeNo);                          //商户订单号
            model.setTradeNo(tradeNo);                                //支付宝交易号
            model.setOperatorId(String.valueOf(operateId));           //操作人
            request.setBizModel(model);
            AlipayTradeCloseResponse response = alipayClient.execute(request);
            //验证返回结果
            if (response != null) {
                String returnCode = response.getCode();
                if (AliPayResultEnum.SUCCESS.getCode().equals(returnCode)) {
                    //验证结果
                    return new AliPayResult(true, response.getBody(), response.getBody());
                } else {
                    return new AliPayResult(false, response.getBody(), response.getSubMsg());
                }
            } else {
                return new AliPayResult(false, AliPayUtil.CLOSE_TRADE_FIELD);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new AliPayResult(false, e.getMessage());
        }
    }
}

